﻿Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Diagnostics.CodeAnalysis
Imports System.Globalization
Imports System.Workflow.Activities
Imports System.Workflow.ComponentModel

Namespace System.Workflow.Activities.Rules
    Public Class RuleEngine
        ' Methods
        Public Sub New(ByVal ruleSet As RuleSet, ByVal objectType As Type)
            Me.New(ruleSet, New RuleValidation(objectType, Nothing), Nothing)
        End Sub

        Public Sub New(ByVal ruleSet As RuleSet, ByVal validation As RuleValidation)
            Me.New(ruleSet, validation, Nothing)
        End Sub

        Friend Sub New(ByVal ruleSet As RuleSet, ByVal validation As RuleValidation, ByVal executionContext As ActivityExecutionContext)
            If Not ruleSet.Validate(validation) Then
                Throw New RuleSetValidationException(String.Format(CultureInfo.CurrentCulture, Messages.RuleSetValidationFailed, New Object() { ruleSet.name }), validation.Errors)
            End If
            Me.name = ruleSet.Name
            Me.validation = validation
            Dim tracer As Tracer = Nothing
            If WorkflowActivityTrace.Rules.Switch.ShouldTrace(TraceEventType.Information) Then
                tracer = New Tracer(ruleSet.Name, executionContext)
            End If
            Me.analyzedRules = Executor.Preprocess(ruleSet.ChainingBehavior, ruleSet.Rules, validation, tracer)
        End Sub

        <SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId:="0#")> _
        Public Sub Execute(ByVal thisObject As Object)
            Me.Execute(New RuleExecution(Me.validation, thisObject, Nothing))
        End Sub

        Friend Sub Execute(ByVal ruleExecution As RuleExecution)
            Dim tracer As Tracer = Nothing
            If WorkflowActivityTrace.Rules.Switch.ShouldTrace(TraceEventType.Information) Then
                tracer = New Tracer(Me.name, ruleExecution.ActivityExecutionContext)
                tracer.StartRuleSet
            End If
            Executor.ExecuteRuleSet(Me.analyzedRules, ruleExecution, tracer, ("RuleSet." & Me.name))
        End Sub

        <SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId:="0#")> _
        Public Sub Execute(ByVal thisObject As Object, ByVal executionContext As ActivityExecutionContext)
            Me.Execute(New RuleExecution(Me.validation, thisObject, executionContext))
        End Sub


        ' Fields
        Private analyzedRules As IList([Of] RuleState)
        Private name As String
        Private validation As RuleValidation
    End Class
End Namespace

